//
//  ABookViewController.m
//  SouthChina
//  通讯录主页改造
//  Copyright (c) 2015年 科创. All rights reserved.
//
#import "ABookViewController.h"
#import "MessageSessionDao.h"
#import "MessageSession.h"
#import "MessageSessionCell.h"
#import "FriendVerifyViewController.h"
#import "GChatViewController.h"
#import "ContactDao.h"
#import "ShowStudentViewController.h"
#import "LocalAddressViewController.h"
#import "SearchGroupViewController.h"
#import "ShowStudentTableViewCell.h"
#define ABOOKTABBAR 101

@interface ABookViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    NSMutableArray *alldata;//存对应的数据
    UILabel *GrpLable;//群组
    NSMutableArray *groupdata;//群组数据
    UILabel *ChatLable;//讨论组
    NSMutableArray *chatdata;//讨论组数据
    NSArray * titleskey; //标题关键字列表
    NSArray * titles; //标题列表
    NSArray * titlePic;//图像
    NSMutableArray *selectedArr;//列表是否展开状态
}
@end

@implementation ABookViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:PUBLIC_ATTENTION_BROADCAST object:nil];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleBarWithBackBtn:@"通讯录"];
    UIView * bodyView = [[[NSBundle mainBundle] loadNibNamed:@"AddressBookHomeView" owner:self options:nil] objectAtIndex:0];
    
    bodyView.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:bodyView];
    
    alldata = [[NSMutableArray alloc] init];
    selectedArr = [[NSMutableArray alloc] init];
    [selectedArr removeAllObjects];
    
    groupdata  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Group' and operate='U' "]];
    chatdata  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Chat' and operate='U' "]];
   
    titles = @[@"我的好友",@"我的同学",@"我的同事",@"我的舍友",@"我的老师",@"我的辅导员",@"我授科的学生",@"我辅导的学生"];
    titleskey =@[@"Friend",@"Classmate",@"Workmate",@"Roommate",@"Teacher",@"Instructor",@"ClassStudent",@"InstruStudent"];
    titlePic = @[@"myfriend.png",@"myclassmate.png",@"myworkmate.png",@"myroommate.png",@"myteacher.png",@"myinstructor.png",@"mystudent.png",@"mystudent.png"];
    
    //绘画群组、讨论组、手机联系人
    _GrpView.backgroundColor = [UIColor colorWithRed:254.0f/255.0f green:127.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
    _GrpView.layer.masksToBounds = YES;
    _GrpView.layer.cornerRadius = 5;
    UIImageView * GrpImg = [[UIImageView alloc] initWithFrame:CGRectMake(28,15, 36, 23)];
    GrpImg.image = [UIImage imageNamed:@"icon_groups.png"];
    [_GrpView addSubview:GrpImg];
    GrpLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 43, 93, 12)];
    GrpLable.text = [NSString stringWithFormat:@"群组(%lu)",(unsigned long)groupdata.count];
    GrpLable.textAlignment = NSTextAlignmentCenter;
    GrpLable.font = [UIFont boldSystemFontOfSize:13.0f];
    GrpLable.textColor =[UIColor whiteColor];
    [_GrpView addSubview:GrpLable];
    UITapGestureRecognizer *singleTapGrp =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickGrpImg:)];
    [_GrpView addGestureRecognizer:singleTapGrp];
    
    //讨论组
    _ChatView.backgroundColor = [UIColor colorWithRed:88.0f/255.0f green:188.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
    _ChatView.layer.masksToBounds = YES;
    _ChatView.layer.cornerRadius = 5;
    UIImageView * ChatImg = [[UIImageView alloc] initWithFrame:CGRectMake(30,15, 32, 24)];
    ChatImg.image = [UIImage imageNamed:@"icon_chats.png"];
    [_ChatView addSubview:ChatImg];
    ChatLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 43, 93, 12)];
    ChatLable.text = [NSString stringWithFormat:@"讨论组(%lu)",(unsigned long)chatdata.count];
    ChatLable.textAlignment = NSTextAlignmentCenter;
    ChatLable.font = [UIFont boldSystemFontOfSize:13.0f];
    ChatLable.textColor =[UIColor whiteColor];
    [_ChatView addSubview:ChatLable];
    UITapGestureRecognizer *singleTapChat =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickChatImg:)];
    [_ChatView addGestureRecognizer:singleTapChat];
    
    //手机联系人
    _MobileAdress.backgroundColor = [UIColor colorWithRed:92.0f/255.0f green:200.0f/255.0f blue:145.0f/255.0f alpha:1.0f];
    _MobileAdress.layer.masksToBounds = YES;
    _MobileAdress.layer.cornerRadius = 5;
    UIImageView * MobileImg = [[UIImageView alloc] initWithFrame:CGRectMake(37,15, 18, 24)];
    MobileImg.image = [UIImage imageNamed:@"icon_tels.png"];
    [_MobileAdress addSubview:MobileImg];
    UILabel *MobileLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 43, 93, 12)];
    MobileLable.text = @"手机联系人";
    MobileLable.textAlignment = NSTextAlignmentCenter;
    MobileLable.font = [UIFont boldSystemFontOfSize:13.0f];
    MobileLable.textColor =[UIColor whiteColor];
    [_MobileAdress addSubview:MobileLable];
    
    UITapGestureRecognizer *singleTapMile =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickMobileImg:)];
    [_MobileAdress addGestureRecognizer:singleTapMile];
    
    //通讯录联系人
    _frequentlyTable.delegate =self;
    _frequentlyTable.dataSource = self;
    _frequentlyTable.bounces = NO;
    
    _frequentlyTable.tableHeaderView = _headview;
    
    
    //搜索框
    _searchLinkman.showsCancelButton=NO;
    _searchLinkman.barStyle=UIBarStyleDefault;
    _searchLinkman.placeholder = @"";
    _searchLinkman.delegate =self;
    //读取数据
    [self refreshTableView];
}

//群组
-(void) onClickGrpImg:(UITapGestureRecognizer *)sender{
    GChatViewController * gchat =[[GChatViewController alloc] initWithNibName:nil bundle:nil];
    gchat.GChatType = @"5";
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:gchat animated:YES];
}

//讨论组
-(void) onClickChatImg:(UITapGestureRecognizer *)sender{
   GChatViewController * gchat =[[GChatViewController alloc] initWithNibName:nil bundle:nil];
   gchat.GChatType = @"4";
   [kAppDelegate.iCSDrawerController.navigationController pushViewController:gchat animated:YES];
}

//手机联系人
-(void) onClickMobileImg:(UITapGestureRecognizer *)sender{
    LocalAddressViewController *localAddress = [[LocalAddressViewController alloc] init];
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:localAddress animated:NO];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"搜索框的点击事件");
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //跳转到通讯录通用搜索页面
    SearchGroupViewController * searchgroup =[[SearchGroupViewController alloc] initWithNibName:nil bundle:nil];
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:searchgroup animated:YES];
    return  NO;//返回NO不显示键盘
}
// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //[self searchBar:searchBar textDidChange:@""];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  alldata.count;
}

//设置view，将替代titleForHeaderInSection方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sIndex = [NSString stringWithFormat:@"%ld",(long)section];
    NSDictionary *dictionary = alldata[section];
    NSArray *arrlist = [dictionary objectForKey:@"Celllist"];
    if (arrlist.count>0) {
        UIView *viewtmp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
        viewtmp.backgroundColor = [UIColor whiteColor];
        
        //图片
        UIImageView * grpCellImg = [[UIImageView alloc] initWithFrame:CGRectMake(5,15, 20, 20)];
        grpCellImg.layer.masksToBounds = YES;
        grpCellImg.layer.cornerRadius = 10;
        NSString *spic = [dictionary objectForKey:@"CellPic"];
        grpCellImg.image = [UIImage imageNamed:spic];
        [viewtmp addSubview:grpCellImg];
        
        //标签
        UILabel *grpCellLable = [[UILabel alloc]initWithFrame:CGRectMake(30, 15, tableView.frame.size.width-30, 20)];
        grpCellLable.text = [NSString stringWithFormat:@"%@(%lu)",[dictionary objectForKey:@"Cellname"],(unsigned long)arrlist.count];
        grpCellLable.textAlignment = NSTextAlignmentLeft;
        grpCellLable.font = [UIFont systemFontOfSize:14.0f];
        [viewtmp addSubview:grpCellLable];
        
        //选择标识
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(tableView.frame.size.width-30, 20, 10, 10)];
        imageView.tag = 20000+section;
        
        //判断是不是选中状态
        if ([selectedArr containsObject:sIndex]) {
            imageView.image = [UIImage imageNamed:@"expanded.png"];
        }
        else
        {
            imageView.image = [UIImage imageNamed:@"unexpand.png"];
        }
        [viewtmp addSubview:imageView];
        
        //按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 320, 40);
        button.tag = 100+section;
        [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
        [viewtmp addSubview:button];
        return  viewtmp;
    }
    else
        return  nil;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 12;
}

-(void) refreshTableView{
    //先清空再加载
    [alldata removeAllObjects];
    for (int i = 0;i<titleskey.count;i++) {
        NSString *sqlWhere = [NSString stringWithFormat:@"where ref_id='%@' and operate='U' and type <> 'O'",titleskey[i]];
        NSMutableArray *arrList = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:sqlWhere]];
       if(arrList.count>0)
       {
           // 名称\图片\用户列表
           NSDictionary *dictionary  = @{@"Cellname":titles[i],@"CellKey":titleskey[i],@"CellPic":titlePic[i],@"Celllist":arrList};
           [alldata addObject:dictionary];
       }
    }
    
    groupdata  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Group' and operate='U' "]];
    chatdata  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Chat' and operate='U' "]];
    GrpLable.text = [NSString stringWithFormat:@"群组(%lu)",(unsigned long)groupdata.count];
    
    ChatLable.text = [NSString stringWithFormat:@"讨论组(%lu)",(unsigned long)chatdata.count];
    
    [_frequentlyTable reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sIndex = [NSString stringWithFormat:@"%ld",(long)section];
    if ([selectedArr containsObject:sIndex]) {   //展开
        
        UIImageView *imageV = (UIImageView *)[_frequentlyTable viewWithTag:20000+section];
        imageV.image = [UIImage imageNamed:@"expanded.png"];
        //我辅导的学生特别处理
        NSDictionary *dictionary = alldata[section];
        NSString *sTitleKey = [dictionary objectForKey:@"CellKey"];
        if([sTitleKey isEqualToString:@"InstruStudent"])
        {
            return 0;
        }
        else
        {
            NSArray *arrList = [dictionary objectForKey:@"Celllist"];
            return arrList.count;
        }
        
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"ShowStudentTableViewCell";
    ShowStudentTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    NSDictionary *dictonary = alldata[indexPath.section];
    NSArray *arrList = [dictonary objectForKey:@"Celllist"];
    Contact *contact = arrList[indexPath.row];
    //名称
    cell.username.text = contact.mNAME;
    cell.username.font = [UIFont systemFontOfSize:13];
    //头像
    NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
    [cell.userimage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    cell.userimage.layer.masksToBounds = YES;
    cell.userimage.layer.cornerRadius = 15;
    //学院
    UILabel *deptLable = [[UILabel alloc]initWithFrame:CGRectMake(160, 15, 120, 20)];
    deptLable.text = contact.mDEPT;
    deptLable.textAlignment = NSTextAlignmentRight;
    deptLable.font = [UIFont systemFontOfSize:11.0f];
    deptLable.textColor = [UIColor grayColor];
    [cell addSubview:deptLable];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)doButton:(UIButton *)sender
{
    NSString *string = [NSString stringWithFormat:@"%ld",sender.tag-100];
    NSLog(@"点击索引：%@",string);
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if ([selectedArr containsObject:string])
    {
        [selectedArr removeObject:string]; //关闭
    }
    else
    {
       NSDictionary *dictonary = alldata[sender.tag-100];
       if([[dictonary objectForKey:@"CellKey"] isEqualToString:@"InstruStudent"]) //进入我辅导的学生页面
        {
           ShowStudentViewController *showstudent = [[ShowStudentViewController alloc] init];
            showstudent.sref_id =@"InstruStudent";
            showstudent.MyStudentType = SHOW_MYSTUDENT;
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:showstudent animated:NO];
        }
        else
        {
             [selectedArr addObject:string]; //展开
        }
    }
    
    [_frequentlyTable reloadData];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dictonary = alldata[indexPath.section];
    NSArray *arrList = [dictonary objectForKey:@"Celllist"];
    Contact * contact = arrList[indexPath.row];
    MessageViewController * message = [[MessageViewController alloc]init];
    NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"2",@"record_DB_ID":contact.mPK_ID,
                           @"recordID":contact.mID};
    message.sessInfo = dicc;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:YES];
    //刷新
    NSLog(@"刷新通讯录");
    [self refreshTableView];
}

@end
